import datetime
import hashlib
import logging

from ability.enums import ErrorCode
from ability.format import CustomResponse, GetPostParaOrNone
from admins.serializers import AdminsSerializer, AdminUpdateSerializer
from django.http.response import HttpResponseRedirect
from rest_framework.exceptions import ValidationError
from ability.models import UserProfile, Admin as SuperAdmin
from django.conf import settings
from rest_framework import viewsets, permissions, mixins
import ability.permissions as pm
from ability.excepts import LogicException,FormException
from rest_framework.response import Response
from study.utils import banned_val
from ability.mixins import ResponseMixin
import traceback
from study.utils import del_login_cookie, set_login_cookie, get_success_url
from django.contrib.auth import  login as auth_login
from ability.enums import trans
# Create your views here.

class Admins(mixins.ListModelMixin, viewsets.GenericViewSet):

  queryset = UserProfile.objects.filter(user_type='A').all().order_by('-id')
  serializer_class = AdminsSerializer
  permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission]

  def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    user_status = self.request.query_params.get('status', None)
    username = self.request.query_params.get('username', None)
    banned = [None, '']
    if str(user_status) in ['1','2','3']:
      queryset = queryset.filter(user_status=trans.status.get(str(user_status)))
    if username not in banned:
      queryset = queryset.filter(username__icontains=username)
    queryset = queryset.order_by('-create_time')
    page = self.paginate_queryset(queryset)
    if page is not None:
      serializer = self.get_serializer(page, many=True)
      return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(queryset, many=True)
    return Response(serializer.data)

class Admin(viewsets.ModelViewSet, ResponseMixin):

  queryset = UserProfile.objects.filter(user_type='A')
  serializer_class = AdminsSerializer
  def retrieve(self, request, *args, **kwargs):
    try:
      print(self.kwargs)
      instance = self.get_object()
      serializer = self.get_serializer(instance)
      self.response_format["data"] = serializer.data
      print(self.response_format)
      self.response_format["error_code"] = 0
      self.response_format["message"] = ""
    except UserProfile.DoesNotExist:
        self.response_format["error_code"] = ErrorCode.parameter_error.value
        self.response_format["message"] = '用户不存在'
    
    return Response(self.response_format)

  def perform_create(self, serializer):

    username = GetPostParaOrNone(self.request.data,"username")
    phone = GetPostParaOrNone(self.request.data,"phone")
    email = GetPostParaOrNone(self.request.data,"email")
    if phone in banned_val:
      raise LogicException('手机号不能为空')
    user = UserProfile.objects.filter(phone=phone, user_type='S').first()
    if user not in ['',None]:
      user_valid_phone = UserProfile.objects.filter(phone=phone).first()
      if user_valid_phone not in ['', None] and  user_valid_phone.id != user.id:
        raise LogicException('手机号已存在')
      user_valid_username = UserProfile.objects.filter(username=username).first()
      if user_valid_username not in banned_val and user_valid_username.id != user.id:
        raise LogicException('用户名已存在')
      user_valid_email = UserProfile.objects.filter(email=email).first()
      if user_valid_email not in banned_val and user_valid_email.id != user.id:
        raise LogicException('邮箱已存在')
      user.phone = phone
      user.email = email
      user.sex = str(self.request.data['sex'])
      user.user_status = str(self.request.data['user_status'])
      user.username = username
      user.real_name = username
      user.user_type = 'A'
      user.create_time = datetime.datetime.now()
      user.save()
      SuperAdmin.addOne(user)
    else:
      if UserProfile.objects.filter(phone=phone).first() not in ['', None]:
        raise LogicException('手机号已存在')

      if username not in banned_val and UserProfile.username_exists(username):
        raise LogicException('用户名已存在')

      if email not in banned_val and UserProfile.email_exists(email):
        raise LogicException('邮箱已存在')
      user = UserProfile()
      user.phone = phone
      user.email = email
      user.sex = str(self.request.data['sex'])
      user.user_status = str(self.request.data['user_status'])
      user.username = username
      user.real_name = username
      user.user_type = 'A'
      user.create_time = datetime.datetime.now()
      user.save()
      # serializer.data['user_type'] = 'A'
      # serializer.save()
      queryuser = UserProfile.objects.get(phone=phone)
      print(queryuser)
      SuperAdmin.addOne(queryuser)

  def create(self, request, *args, **kwargs):
    try:
      self.serializer_class = AdminUpdateSerializer
      self.perform_create(request)
      self.response_format["message"] = "管理员创建成功"
      self.response_format["error_code"] = 0
    except LogicException as e:
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = str(e)
    except Exception as e:
      traceback.print_exc()
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      if str(e).lower().__contains__("email"):
        self.response_format["message"] = "邮箱格式有误，请输入正确的邮箱"
      elif str(e).__contains__("username already exists"):
        self.response_format["message"] = "用户名已存在"
      else :
        self.response_format["message"] = str(e)
    return Response(self.response_format)

  def update(self, request, *args, **kwargs):
    try:
      self.serializer_class = AdminUpdateSerializer
      username = GetPostParaOrNone(self.request.data, "username")
      phone = GetPostParaOrNone(self.request.data, "phone")
      email = GetPostParaOrNone(self.request.data, "email")
      status = GetPostParaOrNone(self.request.data, "user_status")
      if status != 'N' and self.request.user.id==self.kwargs.get("pk"):
        self.response_format["error_code"] = ErrorCode.parameter_error.value
        self.response_format["message"] = "不可以修改当前登录帐号的状态！！！"
        return Response(self.response_format)
      if phone in banned_val:
        raise LogicException('手机号不能为空')
      if UserProfile.objects.filter(phone=phone).exclude(id=self.kwargs.get('pk')).exists():
        raise LogicException('手机号已存在')
      if username in banned_val:
        raise LogicException('用户名不能为空')
      if UserProfile.objects.filter(username=username).exclude(id=self.kwargs.get('pk')).exists():
        raise LogicException('用户名已存在')
      if email in banned_val:
        raise LogicException('邮箱不能为空')
      if UserProfile.objects.filter(email=email).exclude(id=self.kwargs.get('pk')).exists():
        raise LogicException('邮箱已存在')
      super(Admin, self).update(request, *args, **kwargs)
      queryuser = UserProfile.objects.get(id=self.kwargs.get('pk'))
      if (SuperAdmin.objects.filter(user=queryuser).count()==0):
        SuperAdmin.addOne(queryuser)
      self.response_format["message"] = "更新成功"
      self.response_format["error_code"] = 0
    except LogicException as e:
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = str(e)
    except ValidationError as e:
      traceback.print_exc()
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      if str(e).lower().__contains__("email"):
        self.response_format["message"] = "邮箱格式有误，请输入正确的邮箱"
      elif str(e).__contains__("username already exists"):
        self.response_format["message"] = "用户名已存在"
      else :
        self.response_format["message"] = str(e)
    except Exception as e:
      traceback.print_exc()
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = str(e)
    return Response(self.response_format)

  def login(self, request, *args, **kwargs):
      try:
        phone = self.request.query_params.get('phone',None)
        pwd = self.request.query_params.get('pwd',None)

        banned = ['', None]
        if phone in banned:
          self.response_format["message"] = "手机号不存在"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        if pwd in banned:
          self.response_format["message"] = "密码不能为空"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        user = UserProfile.get_by_phone(phone)
        if user is None:
          self.response_format["message"] = "管理员不存在,请联系管理员添加"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        if user.user_type != 'A':
          self.response_format["message"] = "请使用管理员账号进行登录！！！"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        if user.user_status == 'L':
          self.response_format["message"] = "账号已被封禁,请联系管理员/(ㄒoㄒ)/~~"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        if user.user_status == 'C':
          self.response_format["message"] = "此账号已被注销/(ㄒoㄒ)/~~"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        if hashlib.md5(pwd.encode()).hexdigest() != user.pwd:
          self.response_format["message"] = "您输入的密码有误/(ㄒoㄒ)/~~"
          self.response_format["error_code"] = 1006
          return Response(self.response_format)
        else:
          url = get_success_url(user)
          print(url)
        self.response_format["message"] = "登录成功"
        self.response_format["error_code"] = 0
        response = Response(self.response_format)
        del_login_cookie(response)
        set_login_cookie(response, user)
        auth_login(request, user)
        return response
      except Exception as e:
        self.response_format["message"] = str(e)
        self.response_format["error_code"] = 1006
        return Response(self.response_format)
    # phone = self.request.query_params.get('phone', None)
    # if (phone in ['',None]):
    #   self.response_format["error_code"] = 1006
    #   self.response_format["message"] = str("手机号不能为空/ToT/")
    #   raise LogicException("手机号不能为空/ToT/")
    #   # return Response(self.response_format)
    # pwd = self.request.query_params.get('pwd', None)
    # if (pwd in ['',None]):
    #   self.response_format["error_code"] = 1006
    #   self.response_format["message"] = str("密码不能为空/ToT/")
    #   raise LogicException("密码不能为空/ToT/")
    #   # return Response(self.response_format)
    # try:
    #   pwd = hashlib.md5(pwd.encode()).hexdigest()
    #   print("================================")
    #   print(phone)
    #   print(pwd)
    #   print("================================")
    #   queryuser = UserProfile.objects.filter(phone=phone.strip(),pwd=pwd.strip()).first()
    #   if (queryuser is None):
    #     self.response_format["error_code"] = 1006
    #     # self.response_format["message"] = str("账号或密码错误，请重新输入/ToT/")
    #     raise LogicException("账号或密码错误，请重新输入/ToT/")
    #   if (queryuser.user_status != 'N'):
    #     self.response_format["error_code"] = 1006
    #     # self.response_format["message"] = str("当前帐号存在异常，请联系管理员/ToT/")
    #     raise LogicException("请使用管理员账号进行登录！！！")
    #   if (queryuser.user_type != 'A'):
    #     self.response_format["error_code"] = 1006
    #     # self.response_format["message"] = str("当前帐号存在异常，请联系管理员/ToT/")
    #     raise LogicException("当前帐号存在异常，请联系管理员/ToT/")
    #     # return Response(self.response_format)
    #   else :
    #     self.response_format["error_code"] = 0
    #     self.response_format["data"] = "success"
    #     del_login_cookie(Response(self.response_format))
    #     set_login_cookie(Response(self.response_format), queryuser)
    #     auth_login(request, queryuser)
    #     return Response(self.response_format)
    # except LogicException as e:
    #   self.response_format["error_code"] = ErrorCode.parameter_error.value
    #   self.response_format["message"] = str(e)
    # except Exception as e:
    #   traceback.print_exc()
    #   self.response_format["error_code"] = ErrorCode.parameter_error.value
    #   self.response_format["message"] = str(e)
    # return Response(self.response_format)